package com.zzy.demo.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.zzy.demo.common.dto.CodeMsg;
import com.zzy.demo.common.dto.Result;

@Controller
public class LoginController {
	
	 private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
	
	private RequestCache requestCache=new HttpSessionRequestCache();
	
	private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();
	
	/**
	 * 区分json请求   和 url请求
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/authentication/require")
	@ResponseStatus(code=HttpStatus.UNAUTHORIZED)
	@ResponseBody
	public Result<CodeMsg> login(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		SavedRequest savedRequest=requestCache.getRequest(request, response);  //上一个url被缓存
		
		if(null!=savedRequest) {
			String targetUrl=savedRequest.getRedirectUrl();
			LOGGER.debug("请求的url---------"+targetUrl);
			
			//如果不是json请求, 跳转登录页面
			if(!StringUtils.endsWithIgnoreCase(targetUrl, ".json")) {
				//返回html页面
				redirectStrategy.sendRedirect(request, response, "/login");
			}
		}
		
		//返回json
		return Result.error(CodeMsg.SESSION_ERROR);
	}

	
	/**
	 * 跳转登录页
	 * @return
	 */
	@RequestMapping("/login")
	public String login() {
		return "login";
	}


}
